﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataAccessLayer;
using BussinessLayer;
using QLBaoHanh.Template;
using QLBaoHanh.BaoCao;

namespace QLBaoHanh.NghiepVu
{
    public partial class frmPhieuTiepNhan : Form
    {
        private bool _isEditForm;
        private Phien _phien;
        private int _phienId;
        private frmDsPhienTheoTrangThai _callerForm;
        private BindingList<Phien_ThietBiBH> _thietBiBaoHanhList;

        public int PhienId
        {
            set
            {
                _phienId = value;
                //reload LoaiDichVu
                if(_phienId!=0)
                {
                    PhienBO obj = new PhienBO();
                    _phien = obj.GetPhienById(_phienId);
                    //RefreshForm();
                }
            }
        }

        public bool IsEditForm
        {
            set
            {
                _isEditForm = value;
                if (!_isEditForm)
                {
                    FillForm();
                }

            }
            get
            {
                return _isEditForm;
            }
        }

        public frmDsPhienTheoTrangThai CallerForm
        {
            get { return _callerForm; }
            set { _callerForm = value; }
        }


        private void RefreshForm()
        {
            FillForm();
        }

        private void FillForm()
        {
            PhienBO objPhienBO = new PhienBO();
            this.Text = "Phiếu bảo hành sửa chữa ngay";
            if (_isEditForm)
            {
                Phien aPhien = objPhienBO.GetPhienById(_phienId);
                txtSoPhieu.Text = aPhien.SoBienNhan;
                txtMaKH.Text = aPhien.KhachHang.Ma;
                txtTenKH.Text = aPhien.KhachHang.Ten;
                txtSDT.Text = aPhien.KhachHang.Mobile;
                txtDiaChi.Text = aPhien.KhachHang.DiaChi;
                txtEmail.Text = aPhien.KhachHang.Email;
                txtNoiDung.Text = aPhien.NoiDung;
                cboNVNhan.Items.Add(aPhien.NhanVien.Ten);
                cboNVNhan.Text = aPhien.NhanVien.Ten;
            }
            else
            {
                txtSoPhieu.Text = objPhienBO.GenerateMaPhien();
                txtMaKH.Text = KhachHangBO.getInstance.GenerateMaKhachHang();
                cboNVNhan.Items.Add(frmMain.CurrentNhanVien.Ten);
                cboNVNhan.Text = frmMain.CurrentNhanVien.Ten;
                //chkTimKiem.Checked = false;
            }
        }

        private void ChangeTimKiem()
        {
            //Enable cboTimKiem and disable form them khach hang
            bool isTimKiem = chkTimKiem.Checked;
            cboTimKiem.Enabled = isTimKiem;
            txtMaKH.Enabled = !isTimKiem;
            txtDiaChi.Enabled = !isTimKiem;
            txtSDT.Enabled = !isTimKiem;
            txtEmail.Enabled = !isTimKiem;
            txtMaKH.Text = "";
            txtTenKH.Text = "";
            txtEmail.Text = "";
            txtSDT.Text = "";
            txtDiaChi.Text = "";
            if (isTimKiem)
            {
                FillCboTimKiem();
            }
            else
            {
                FillForm();
            }
        }

        private void FillKhachHangDuocChon(int inKhachHangId)
        {
            if (inKhachHangId == 0) return;
            KhachHang KhachHangChon = KhachHangBO.getInstance.GetKhachHangById(inKhachHangId);
            txtMaKH.Text = KhachHangChon.Ma;
            txtTenKH.Text = KhachHangChon.Ten;
            txtSDT.Text = KhachHangChon.Mobile;
            txtDiaChi.Text = KhachHangChon.DiaChi;
            txtEmail.Text = KhachHangChon.Email;
        }

        private void FillCboTimKiem()
        {
            List<KhachHang> KhachHangData = KhachHangBO.getInstance.GetAllKhachHang().ToList();
            KhachHang BlankKH = new KhachHang();
            BlankKH.Id = 0;
            BlankKH.Ten = "- - - - - - - -";
            KhachHangData.Insert(0, BlankKH);
            cboTimKiem.DataSource = KhachHangData;
            cboTimKiem.DisplayMember = "Ten";
            cboTimKiem.ValueMember = "Id";
            cboTimKiem.SelectedIndex = 0;
        }

        /// <summary>
        /// Add ThietBiBaoHanh
        /// Create and show form add
        /// </summary>
        private void AddThietBiBaoHanh()
        {
            frmThietBiBHDetail frmObj = SingletonFormProvider.GetInstance<frmThietBiBHDetail>(this);
            frmObj.IsEditForm = false;
            //frmObj.MdiParent = this.ParentForm;
            frmObj.CallerForm = this;
            frmObj.ShowDialog();
            //frmObj.Focus();
        }

        /// <summary>
        /// Edit ThietBiBaoHanh
        /// Create and show form edit
        /// </summary>
        /// <param name="ThietBiBaoHanhId"></param>
        private void EditThietBiBaoHanh(int Phien_ThietBiBaoHanhId)
        {
            if (Phien_ThietBiBaoHanhId == 0)
            {
                //Must choose a row
                MessageBox.Show("Phải chọn thiết bị bảo hành!", "Ds thiết bị bảo hành", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                frmThietBiBHDetail frmObj = SingletonFormProvider.GetInstance<frmThietBiBHDetail>(this);
                frmObj.IsEditForm = true;
                frmObj.Phien_ThietBiBHId = Phien_ThietBiBaoHanhId;
                //frmObj.MdiParent = this.ParentForm;
                frmObj.CallerForm = this;
                frmObj.ShowDialog();
                //frmObj.Focus();
            }
        }

        /// <summary>
        /// Delete a ThietBiBaoHanh
        /// </summary>
        /// <param name="ThietBiBaoHanhId">ThietBiBaoHanhId</param>
        private void DeleteThietBiBaoHanh(int ThietBiBaoHanhId)
        {
            if (ThietBiBaoHanhId == 0)
            {
                //Must choose a row
                MessageBox.Show("Phải chọn thiết bị bảo hành!", "Ds thiết bị bảo hành", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (MessageBox.Show("Bạn chắc chắn muốn xóa?"
                    , "thiết bị bảo hành", MessageBoxButtons.YesNo
                    , MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    ThietBiBaoHanhBO.getInstance.DelThietBiBaoHanh(ThietBiBaoHanhId);
                }
            }
        }

        /// <summary>
        /// Get selected item of grid view
        /// </summary>
        /// <returns>0 - not selected else return id</returns>
        private int getSelectedId()
        {
            int Id = 0;
            if (dgvTbiBH.SelectedRows.Count != 0)
            {
                Id = (int)dgvTbiBH.SelectedRows[0].Cells["Id"].Value;
            }
            return Id;
        }
        /// <summary>
        /// Load data to grid
        /// </summary>
        /// 

        private void LoadGrid()
        {
            int CurrentRowIndex = 0;
            if (dgvTbiBH.CurrentRow != null)
            {
                CurrentRowIndex = dgvTbiBH.CurrentRow.Index;
            }

            var DataList = _thietBiBaoHanhList.Where<Phien_ThietBiBH>(aObj => aObj.ModifyState != RecordState.DEL_STATE).Select(o => (Phien_ThietBiBH)o).OrderBy(b => b.Id);
            dgvTbiBH.AutoGenerateColumns = false;
            dgvTbiBH.DataSource = new BindingList<Phien_ThietBiBH>(DataList.ToList());
            //if current row index !=0 then selected it
            if (CurrentRowIndex != 0)
            {
                this.dgvTbiBH.Rows[CurrentRowIndex -1].Selected = true;
            }
            //else Selected to first items.
            if (dgvTbiBH.Rows.Count > 0 && dgvTbiBH.SelectedRows.Count == 0)
            {
                this.dgvTbiBH.Rows[dgvTbiBH.Rows.Count - 1].Selected = true;
            }
        }

        public void AddThietBiBaoHanhData(Phien_ThietBiBH inObj)
        {
            inObj.RecordCreatedTime = DateTime.Now;
            _thietBiBaoHanhList.Add(inObj);
            LoadGrid();
        }
        
        private int SaveKhachHang()
        {
            KhachHang obj;
            if (IsEditForm)
            {
                obj = KhachHangBO.getInstance.GetKhachHangById((int)_phien.KhachHangId);
                obj.Ten = txtTenKH.Text;
                obj.DiaChi = txtDiaChi.Text;
                obj.Mobile = txtSDT.Text;
                obj.Email = txtEmail.Text;
                KhachHangBO.getInstance.UpdateKhachHang(obj);
                return obj.Id;
            } 
            else
            {
                obj = new KhachHang();
                obj.Ma = txtMaKH.Text;
                obj.Ten = txtTenKH.Text;
                obj.Mobile = txtSDT.Text;
                obj.DiaChi = txtDiaChi.Text;
                KhachHangBO.getInstance.InsertKhachHang(obj);
                return KhachHangBO.getInstance.GetLastRecord().Id;
            }
            
        }
        private int SavePhien(int inKhachHangId)
        {
            Phien obj;
            PhienBO objPhienBO = new PhienBO();
            if (IsEditForm)
            {
                obj = objPhienBO.GetPhienById(_phienId);
                obj.KhachHangId = inKhachHangId;
                obj.ThoiGianNhan = dtpThoiGianNhan.Value;
                //obj.NhanVienId = Convert.ToInt16(cboNVNhan.SelectedValue);
                obj.NhanVienId = frmMain.CurrentNhanVien.Id;
                obj.NoiDung = txtNoiDung.Text;
                objPhienBO.UpdatePhien(obj);
                return obj.Id;
            } 
            else
            {
                obj= new Phien();
                obj.TrangThaiPhienId = (int)MyCommon.TrangThaiPhien.ThaoTacNgay;
                obj.SoBienNhan = txtSoPhieu.Text;
                obj.ThoiGianNhan = dtpThoiGianNhan.Value;
                //obj.NhanVienId = Convert.ToInt16(cboNVNhan.SelectedValue);
                obj.NhanVienId = frmMain.CurrentNhanVien.Id;
                obj.KhachHangId = inKhachHangId;
                obj.NoiDung = txtNoiDung.Text;
                objPhienBO.InsertPhien(obj);
                return objPhienBO.GetLastRecord().Id;
            }
        }
        private void SavePhien_ThietBi(int inPhienId)
        {
            foreach (Phien_ThietBiBH item in _thietBiBaoHanhList)
            {
                if (item.ModifyState == RecordState.ADD_STATE)
                {
                    item.PhienId = inPhienId;
                    item.TrangThaiThietBiBHID = (int)MyCommon.TrangThaiThietBiBH.BaoHanhSuaChuaNgay;
                    Phien_ThietBiBHBO.getInstance.InsertPhien_ThietBiBH(item);

                    //Luu lai lich su Bao hanh
                    LichSuBH objLichSu = new LichSuBH();
                    objLichSu.LoaiLichSu = (int)MyCommon.LoaiLichSu.LichSuHeThong;
                    objLichSu.Phien_ThietBiBHId = Phien_ThietBiBHBO.getInstance.GetLastRecord().Id;
                    objLichSu.NVThucHienId = frmMain.CurrentNhanVien.Id;
                    objLichSu.ThoiGian = DateTime.Now;
                    objLichSu.NoiDung = "Nhận thiết bị từ khách hàng";
                    LichSuBHBO.getInstance.InsertLichSuBH(objLichSu);

                    //Add them 1 lan BH cho thiet bi
                    ThietBiBaoHanh aTBBH = ThietBiBaoHanhBO.getInstance.GetThietBiBaoHanhById(item.ThietBiBHId);
                    if (aTBBH.LanBH == null || aTBBH.LanBH == 0)
                    {
                        aTBBH.LanBH = 1;
                    } 
                    else
                    {
                        aTBBH.LanBH = aTBBH.LanBH + 1;
                    }
                    ThietBiBaoHanhBO.getInstance.UpdateThietBiBaoHanh(aTBBH);
                }
                else if ((item.ModifyState == RecordState.DEL_STATE) && (item.Id !=0) )
                {
                    //Delete from data base
                    Phien_ThietBiBHBO.getInstance.DelPhien_ThietBiBH(item.Id);
                    //Bo di  1 lan BH cho thiet bi
                    //Add them 1 lan BH cho thiet bi
                    ThietBiBaoHanh aTBBH = ThietBiBaoHanhBO.getInstance.GetThietBiBaoHanhById(item.ThietBiBHId);
                    if (aTBBH.LanBH == null)
                    {
                        aTBBH.LanBH = 0;
                    }
                    else if ( aTBBH.LanBH < 1)
                    {
                        aTBBH.LanBH = 0;
                    }
                    else
                    {
                        aTBBH.LanBH = aTBBH.LanBH - 1;
                    }
                    ThietBiBaoHanhBO.getInstance.UpdateThietBiBaoHanh(aTBBH);
                }
            }
        }

        private void ReadPhienData()
        {
            PhienBO objPhienBO = new PhienBO();
            //Load data from View_Phien_ThietBiBaoHanh
            List<View_Phien_ThietBiBH> PhienDataList = objPhienBO.GetThongTinThietBiByPhienId(_phienId).ToList<View_Phien_ThietBiBH>();
            //Built _phien_ThietBiBaoHanhList
            foreach (View_Phien_ThietBiBH item in PhienDataList)
            {
                Phien_ThietBiBH APhien_ThietBiBH = new Phien_ThietBiBH();
                APhien_ThietBiBH.Id = item.Phien_ThietBiBHId;
                APhien_ThietBiBH.PhienId = item.PhienId;
                APhien_ThietBiBH.ThietBiBHId = item.ThietBiBHId;
                APhien_ThietBiBH.RecordCreatedTime = DateTime.Now;
                APhien_ThietBiBH.MaThietBiBaoHanh = item.MaThietBi;
                APhien_ThietBiBH.TenThietBiBaoHanh = item.TenThietBi;
                APhien_ThietBiBH.Serial = item.Serial;
                APhien_ThietBiBH.Model = item.Model;
                APhien_ThietBiBH.DichVuId = item.DichVuId;
                APhien_ThietBiBH.TenLoaiDichVu = item.TenLoaiDichVu;
                APhien_ThietBiBH.GhiChu = item.GhiChuPhien_ThietBiBH;
                APhien_ThietBiBH.Loi = item.Loi;
                APhien_ThietBiBH.NCCId = (int)item.NCCId;
                APhien_ThietBiBH.NSXId = (int)item.NSXId;
                //Thoi han bao hanh = ngay mua + Tgian BH
                APhien_ThietBiBH.ThoiHanBaoHanh = item.NgayMua.Value.AddMonths((int)item.TGianBH);
                APhien_ThietBiBH.SoLuong = item.SoLuong;
                APhien_ThietBiBH.ModifyState = RecordState.NONE_STATE;
                _thietBiBaoHanhList.Add(APhien_ThietBiBH);
            }
        }

        private void SetVisibilityPrintPhieuTiepNhan(bool inVisible)
        {
            lblMauIn.Visible = inVisible;
            cboMauIn.Visible = inVisible;
            btnInPhieu.Visible = inVisible;
            btnXemPhieu.Visible = inVisible;
            cboMauIn.SelectedIndex = 0;
        }

        public frmPhieuTiepNhan(bool inIsEditForm, int inPhienId, frmDsPhienTheoTrangThai inCallerForm)
        {
            InitializeComponent();
            
            _isEditForm = inIsEditForm;
            _phien = null;
            PhienId = inPhienId;
            _callerForm = inCallerForm;
            _thietBiBaoHanhList = new BindingList<Phien_ThietBiBH>();
            if (_isEditForm)
            {
                ReadPhienData();
            }
        }

        private void frmPhieuTiepNhan_Load(object sender, EventArgs e)
        {
            FillForm();
            LoadGrid();
            if (_isEditForm)
            {
                SetVisibilityPrintPhieuTiepNhan(true);
            } 
            else
            {
                SetVisibilityPrintPhieuTiepNhan(false);
            }
        }

        private void btnDelTBi_Click(object sender, EventArgs e)
        {
            if (dgvTbiBH.SelectedRows.Count > 0)
            {
                Phien_ThietBiBH focusObject;
                //Neu phien thiet bi Id !=0 thi lam theo Id khong thi lam theo thoi gian khoi tao
                int Phien_ThietBiId = (int)dgvTbiBH.SelectedRows[0].Cells["Id"].Value;
                if (Phien_ThietBiId != 0)
                {
                    focusObject = _thietBiBaoHanhList.Where<Phien_ThietBiBH>(aObj => aObj.Id == Phien_ThietBiId).SingleOrDefault<Phien_ThietBiBH>();
                }
                else
                {
                    //Phien_ThietBiBH focusObject = _thietBiBaoHanhList.Where<Phien_ThietBiBH>(aObj => aObj.RecordCreatedTime == TimeCreated).SingleOrDefault<Phien_ThietBiBH>();
                    DateTime TimeCreated = (DateTime)dgvTbiBH.SelectedRows[0].Cells["RecordCreatedTime"].Value;
                    focusObject = _thietBiBaoHanhList.Where<Phien_ThietBiBH>(aObj => aObj.RecordCreatedTime == TimeCreated).SingleOrDefault<Phien_ThietBiBH>();
                }
                if(focusObject != null)
                {
                    focusObject.ModifyState = RecordState.DEL_STATE;
                }
            }
            
            LoadGrid();
        }

        private void btnEditTBi_Click(object sender, EventArgs e)
        {
            //_thietBiBaoHanhList.
        }

        private void btnAddTBi_Click(object sender, EventArgs e)
        {
            AddThietBiBaoHanh();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool isKhachHangExist = false;
            int KhachHangId = 0;
            //Kiem tra da nhap khach hang chua?
            if (chkTimKiem.Checked)
            {
                int a = cboTimKiem.FindStringExact(cboTimKiem.Text);
                if (a <= 0)
                {
                    MessageBox.Show("Phải chọn khách hàng!", "Phiếu tiếp nhận", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                isKhachHangExist = true;
                KhachHangId = (int)cboTimKiem.SelectedValue;
            } 
            else
            {
                if (!ValidateKhachHang()) return;
            }

            if (!isKhachHangExist)
            {
                KhachHangId = SaveKhachHang();
            }
            int PhienId = SavePhien(KhachHangId);
            SavePhien_ThietBi(PhienId);
            _callerForm.RefreshForm();
            this.Close();
        }

        private bool ValidateKhachHang()
        {
            bool isValid = true;
            if (txtTenKH.Text.Trim() == "")
            {
                MessageBox.Show("Phải nhập tên khách hàng !", "Phiếu tiếp nhận", MessageBoxButtons.OK, MessageBoxIcon.Error);
                isValid = false;
            }
            return isValid;
        }
        

        private void btnHuy_Click(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {

        }

        private void btnXemPhieu_Click(object sender, EventArgs e)
        {
            //Xem mau in phieu tiep nhan dang duoc chon
            NghiepVuBO objNghiepVuBO = new NghiepVuBO();
            IEnumerable<View_PhieuTiepNhan> data = objNghiepVuBO.GetReportPhieuTiepNhanById(_phienId);
            frmReportViewer<View_PhieuTiepNhan> frmViewer = new frmReportViewer<View_PhieuTiepNhan>(MyCommon.MyReportType.Report_PhieuTiepNhan, data, false);
            frmViewer.Show();
        }

        private void btnInPhieu_Click(object sender, EventArgs e)
        {
            NghiepVuBO objNghiepVuBO = new NghiepVuBO();
            IEnumerable<View_PhieuTiepNhan> data = objNghiepVuBO.GetReportPhieuTiepNhanById(_phienId);
            frmReportViewer<View_PhieuTiepNhan> frmViewer = new frmReportViewer<View_PhieuTiepNhan>(MyCommon.MyReportType.Report_PhieuTiepNhan, data, true);
        }

        private void chkTimKiem_CheckedChanged(object sender, EventArgs e)
        {
            ChangeTimKiem();
        }

        private void cboTimKiem_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboTimKiem.SelectedItem == null) return;
            int KhachHangId = 0;
            try
            {
                KhachHangId = Convert.ToInt32(cboTimKiem.SelectedValue);
            }
            catch (System.Exception ex)
            {

            }
            FillKhachHangDuocChon(KhachHangId);
        }


    }
}
